#include "debug_PmuDwt.h"

/**
 * @brief This function is used to initialize the DWT module
 * @param void
 * @return none
 */
void PMU_DWT_Initialize(void)
{
  /* enable the trace functionality */
  PMU_CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA;
  /* clear DWT counter */
  PMU_DWT->CYCCNT = 0U;
  /* enable DWT cycle counter */
  PMU_DWT->CTRL |= DWT_CTRL_CYCCNTENA;
}

/**
 * @brief This function is used to de-initialize the DWT module
 * @param void
 * @return none
 */
void PMU_DWT_DeInitialize(void)
{
  /* disable the trace functionality */
  PMU_CoreDebug->DEMCR &= ~CoreDebug_DEMCR_TRCENA;
  /* clear DWT counter */
  PMU_DWT->CYCCNT = 0U;
  /* disable DWT cycle counter */
  PMU_DWT->CTRL &= ~DWT_CTRL_CYCCNTENA;
}

/**
 * @brief Microsecond Delay function.
 * 
 * @param delay_us 
 */
void PMU_DWT_DelayUs(uint32_t delay_us)
{
  uint32_t startCount, endCount;

  /* Calculate the end count for the given delay */
  endCount = (CPU_CLOCK_FREQ / 1000000U) * delay_us;
  PMU_DWT->CYCCNT = 0;
  startCount = PMU_DWT->CYCCNT;
  while((PMU_DWT->CYCCNT - startCount) < endCount)
  {
    /* Do Nothing */
  }
}

/**
 * @brief Millisecond.
 * 
 * @param delay_ms 
 */
void PMU_DWT_DelayMs(uint32_t delay_ms)
{
    uint32_t startCount, endCount;
  
    /* Calculate the end count for the given delay */
    endCount = (CPU_CLOCK_FREQ / 1000U) * delay_ms;
    PMU_DWT->CYCCNT = 0;
    startCount = PMU_DWT->CYCCNT;
    while((PMU_DWT->CYCCNT - startCount) < endCount)
  {
    /* Do Nothing */
  }
}



